<?php
namespace app\modules\admin\controllers;

use app\controllers\UploadControllerTrait;
use app\models\ManagerLog;
use app\models\System;
use app\models\SystemMessage;
use app\models\Task;
use Yii;
use yii\data\Pagination;
use yii\helpers\FileHelper;
use yii\helpers\Inflector;
use yii\helpers\Url;
use yii\web\NotFoundHttpException;
use yii\web\ServerErrorHttpException;
use yii\web\UploadedFile;
use yii\web\ForbiddenHttpException;

/**
 * 系统管理
 *
 * Class SystemController
 * @package app\modules\admin\controllers
 */
class SystemController extends BaseController
{
    /**
     * 系统设置
     * @throws ForbiddenHttpException
     * @throws ServerErrorHttpException
     * @return array|string
     */
    public function actionConfig()
    {
        if (!$this->manager->can('system/config')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        if ($this->isPost()) {
            $category = Yii::$app->request->get('category');
            if (empty($category)) {
                return [
                    'message'=>'参数错误。'
                ];
            }
            $config_list = System::find()->andWhere(['category'=>$category])->all();
            $post = Yii::$app->request->post();
            foreach ($config_list as $config) {
                /* @var $config System */
                $type = json_decode($config->type, true);
                if ($type['type'] == 'file') {
                    $_file = UploadedFile::getInstanceByName($config->name);
                    if (!empty($_file)) {
                        $path = Yii::$app->params['upload_path'] . '/system/';
                        if (!file_exists($path)) {
                            if (!FileHelper::createDirectory($path)) {
                                throw new ServerErrorHttpException('无法创建目录：' . $path);
                            }
                        }
                        $fileName = substr(uniqid(md5(rand()), true), 0, 10);
                        $fileName .= '-' . Inflector::slug($_file->baseName);
                        $fileName .= '.' . $_file->extension;
                        if (!$_file->saveAs($path . '/' . $fileName)) {
                            throw new ServerErrorHttpException('无法保存文件：' . $fileName);
                        }
                        $config->value = $fileName;
                    }
                } else {
                    $config->value = $post[$config->name];
                }
                $config->save();
            }
            Yii::$app->session->addFlash('success', '数据已保存。');
        }
        return $this->render('config', [
            'show_category'=>Yii::$app->request->get('category', '系统设置')
        ]);
    }

    /**
     * 文件上传AJAX接口
     * @see \app\controllers\UploadControllerTrait
     */
    use UploadControllerTrait;

    /**
     * 群发消息列表
     * @throws ForbiddenHttpException
     * @return string
     */
    public function actionMessage()
    {
        if (!$this->manager->can('system/message')) {
            throw new ForbiddenHttpException('没有权限');
        }
        $query = SystemMessage::find();
        $query->andFilterWhere(['like', 'title', Yii::$app->request->get('search_title')]);
        $pagination = new Pagination(['totalCount'=>$query->count()]);
        $model_list = $query->orderBy('id DESC')->offset($pagination->offset)->limit($pagination->limit)->all();
        return $this->render('message', [
            'model_list'=>$model_list,
            'pagination'=>$pagination
        ]);
    }

    /**
     * 群发消息
     * @throws ForbiddenHttpException
     * @return string
     */
    public function actionMessageEdit()
    {
        if (!$this->manager->can('system/message')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $model = new SystemMessage();
        $model->time = time();
        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->save()) {
            ManagerLog::info($this->manager->id, '', '群发消息：' . print_r($model->attributes, true));
            Yii::$app->session->addFlash('success', '数据已保存。');
            Yii::$app->session->setFlash('redirect', json_encode([
                'url'=>Url::to(['/admin/system/message']),
                'txt'=>'群发消息列表'
            ]));
        }
        return $this->render('message_edit', [
            'model'=>$model
        ]);
    }

    /**
     * 定时任务
     * @throws ForbiddenHttpException
     * @return string
     */
    public function actionTask()
    {
        if (!$this->manager->can('system/task')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $query = Task::find();
        $pagination = new Pagination(['totalCount'=>$query->count()]);
        $model_list = $query->offset($pagination->offset)->limit($pagination->limit)->all();
        return $this->render('task', [
            'model_list'=>$model_list,
            'pagination'=>$pagination
        ]);
    }

    /**
     * 定时任务详情
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     * @return string
     */
    public function actionTaskView()
    {
        if (!$this->manager->can('system/task')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $id = Yii::$app->request->get('id');
        $task = Task::findOne($id);
        if (empty($task)) {
            throw new NotFoundHttpException('没有找到定时任务信息。');
        }
        return $this->render('task_view', [
            'task'=>$task
        ]);
    }

    /**
     * 删除定时任务AJAX接口
     * @throws ForbiddenHttpException
     * @return array
     */
    public function actionDeleteTask()
    {
        if (!$this->manager->can('system/task')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $id = Yii::$app->request->get('id');
        $model = Task::findOne($id);
        if (empty($model)) {
            return [
                'message'=>'没有找到任务信息。'
            ];
        }
        $model->delete();
        ManagerLog::info($this->manager->id, '', '删除用户定时任务：' . print_r($model->attributes, true));
        return [
            'result'=>'success'
        ];
    }
}
